<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>
      <el-input v-model="params.name" clearable placeholder="请输入内容" class="search-main" />
      <el-button type="primary" @click="searchFn">查询</el-button>
    </div>
    <div class="create-container">
      <el-button type="primary" @click="$router.push('/add-ep')">添加企业</el-button>
    </div>
    <!-- 表格区域 -->
    <div v-auth-dir="`park:enterprise:list`" class="table">
      <el-table style="width: 100%" :data="enterpriseList" @expand-change="expandHandle">
        <!-- 新增：展开部分 -->
        <el-table-column type="expand">
          <template #default="scope">
            <el-table :data="scope.row.list">
              <el-table-column label="租赁楼宇" width="320" prop="buildingName" />
              <el-table-column label="租赁起始时间" prop="startTime" />
              <el-table-column label="租赁结束时间" prop="endTime" />
              <el-table-column label="合同状态" prop="status">
                <template #default="props">
                  <el-tag :type="formatterStatus(props.row.status)">{{ TYPEMAP[props.row.status] }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180">
                <!-- 目标 合同状态 0 1 2 3(待生效、生效中、已到期、已退租)
                 0：退租，删除
                 1：续租、退租
                 2：续租、退租
                 3：删除 -->
                <template #default="{row}">
                  <el-button
                    v-auth-dir="`park:rent:add_surrender`"
                    size="mini"
                    type="text"
                    :disabled="!(row.status===1||row.status===2)"
                    @click="renewRentFn(row,scope)"
                  >续租</el-button>
                  <el-button v-auth-dir="`park:rent:add_surrender`" size="mini" type="text" :disabled="row.status===3" @click="backRentFn(row.id)">退租</el-button>
                  <el-button v-auth-dir="`park:rent:remove`" size="mini" type="text" :disabled="!(row.status===0||row.status===3)" @click="deleteRentFn(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" />
        <el-table-column label="企业名称" width="320" prop="name" />
        <el-table-column label="联系人" prop="contact" />
        <el-table-column
          label="联系电话"
          prop="contactNumber"
        />
        <el-table-column label="操作">
          <template v-slot:default="scope">
            <el-button v-auth-dir="`park:rent:add_surrender`" size="mini" type="text" @click="showAddRentDialog(scope.row.id)">添加合同</el-button>
            <el-button v-auth-dir="`park:enterprise:query`" size="mini" type="text" @click="$router.push(`/ep-detail?id=${scope.row.id}`)">查看</el-button>
            <el-button size="mini" type="text" @click="editRent(scope.row.id)">编辑</el-button>
            <el-button v-auth-dir="`park:enterprise:remove`" size="mini" type="text" @click="delExterprise(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
      <el-pagination
        layout="total, prev, pager, next"
        :total="enterpriseTotal"
        :page-size="params.pageSize"
        @current-change="currentChangeFn"
      />
    </div>
    <!-- 新增合同对话框 -->
    <el-dialog :title="title" :visible.sync="rentDialogVisible" width="580px" @close="closeDialog">
      <!-- 表单区域 -->
      <div class="form-container" />
      <!-- label-position：表单域上 label 值在表单域中的位置 -->
      <el-form ref="addForm" :model="rentForm" :rules="rentRules" label-position="top">
        <el-form-item label="租赁楼宇" prop="buildingId">
          <el-select v-if="title!=='续租合同'" v-model="rentForm.buildingId" placeholder="请选择" :disabled="title==='续租合同'">
            <el-option
              v-for="item in rentBuildList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
          <span v-else>{{ buildingName }}</span>
        </el-form-item>
        <el-form-item label="租赁起止日期" prop="rentTime">
          <el-date-picker
            v-model="rentForm.rentTime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item label="租赁合同" prop="contractId">
          <el-upload
            action="#"
            :http-request="uploadHandle"
            :before-upload="beforeUpload"
            :file-list="contractList"
            :limit="1"
          >
            <el-button size="small" type="primary" plain>上传合同文件</el-button>
            <!-- slot="tip" 提示说明文字 旧语法
                 slot="tip" 等价于 v-slot:tip 或者 #tip

                 slot-scope="scope" 等价于 v-slot="scope"
            -->
            <div slot="tip" class="el-upload__tip">支持扩展名：.doc .pdf, 文件大小不超过5M</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button size="mini" @click="closeDialog">取 消</el-button>
        <el-button size="mini" type="primary" @click="confirmAdd">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import { createRentAPI, delEnterpriseAPI, deleteRentAPI, getEnterpriseListAPI, getRentBuildListAPI, getRentListAPI, outRentAPI, uploadAPI } from '@/apis/park'
export default {
  data() {
    return { // 查询参数对象
      params: {
        page: 1,
        pageSize: 2,
        name: '' // 查询企业名字
      },
      enterpriseList: [], // 企业列表
      enterpriseTotal: 0, // 企业列表总数
      rentDialogVisible: false, // 新增合同对话框显示/隐藏
      rentForm: {
        buildingId: null, // 楼宇id
        contractId: null, // 合同id
        contractUrl: '', // 合同Url
        enterpriseId: null, // 企业id
        type: 0, // 合同类型 0为添加 1为续签
        rentTime: [] // 合同时间
      },
      rentRules: {
        buildingId: [
          { required: true, message: '请选择楼宇', trigger: 'change' }
        ],
        rentTime: [
          { required: true, message: '请选择租赁日期', trigger: 'change' }
        ],
        contractId: [
          { required: true, message: '请上传合同文件' }
        ]
      },
      // 租赁楼宇列表
      rentBuildList: [],
      contractList: [], // 合同文件列表
      TYPEMAP: {
        0: '待生效',
        1: '生效中',
        2: '已到期',
        3: '已退租'
      },
      title: '',
      buildingName: ''
    }
  },
  created() {
    this.getList()
    this.getRentBuildList()
  },
  methods: { // 删除租赁合同
    async deleteRentFn(id) {
      this.$confirm('确认删除该合同吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await deleteRentAPI(id)
        this.getList()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      })
    },
    renewRentFn(row, scope) { // 续租合同
      this.title = '续租合同'
      this.rentDialogVisible = true
      this.rentForm.buildingId = row.buildingId
      // console.log(scope)
      this.buildingName = row.buildingName
      // console.log()
      this.rentForm.enterpriseId = scope.row.id
      const newDate1 = new Date((new Date(row.endTime)).getTime() + 24 * 60 * 60 * 1000)
      const newDate2 = new Date((new Date(row.endTime)).getTime() + 24 * 60 * 60 * 1000 * 2)
      const DateStr1 = newDate1.toLocaleDateString()
      const DateStr2 = newDate2.toLocaleDateString()
      const formattedDate1 = DateStr1.replace(/\//g, '-')
      const formattedDate2 = DateStr2.replace(/\//g, '-')
      this.rentForm.rentTime = [formattedDate1, formattedDate2]
    },
    async getList() { // 获取列表
      const res = await getEnterpriseListAPI(this.params)
      // console.log(res)
      // 问题：运行后增加的对象的新属性，没办法让 Vue 正确的劫持到数据的变化从而更新视图
      // 原因：Vue2 用的 Object.defineProperty 劫持对象的每个属性的 setter（赋） 和 getter(取)
      // 解决：在我给 enterpriseList Vue 的属性赋值让它被劫持前，后端的数据对象里先添加一个 list，再传给vue的属性
      const list = res.data.rows.map(obj => {
        return {
          ...obj,
          list: []
        }
      })
      this.enterpriseList = list
      this.enterpriseTotal = res.data.total
    }, // 列表切换
    currentChangeFn(page) {
      this.params.page = page
      this.getList()
    }, // 查询
    searchFn() {
      this.getList()
    },
    // 编辑点击事件
    editRent(id) {
      this.$router.push({
        path: '/add-ep',
        query: {
          id
        }
      })
    }, // 删除企业
    delExterprise(id) {
      this.$confirm('确认删除该企业吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delEnterpriseAPI(id)
        this.getList()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      })
    }, // 添加合同点击事件
    showAddRentDialog(id) {
      this.title = '添加合同'
      this.rentForm.enterpriseId = id
      this.rentDialogVisible = true
      // console.log(id)
    },
    // 关闭
    closeDialog() {
      this.rentDialogVisible = false
    }, // 获取可租赁的楼宇列表
    async getRentBuildList() {
      const res = await getRentBuildListAPI()
      // console.log(res)
      this.rentBuildList = res.data
    }, // 上传租赁合同文件
    async uploadHandle(file) {
      // 本地磁盘 -> 浏览器 -> 提交到服务器上
      // 后台返回此文件在服务器的 url 和 id值
      console.log(file)

      const fd = new FormData()
      fd.append('file', file.file)
      fd.append('type', 'contract')
      const res = await uploadAPI(fd)
      console.log(res)
      this.rentForm.contractUrl = res.data.url
      this.rentForm.contractId = res.data.id
    }, // 租赁合同文件校验
    beforeUpload(file) {
      // console.log(file)
      const list = ['application/pdf', 'application/msword'] // MIME 媒体类型 (参考mdn) 是一种所有计算机软件共同遵守的一种媒体类型
      const isFile = list.includes(file.type)
      const isLt5M = file.size / 1024 / 1024 < 5

      if (!isFile) {
        this.$message.error('上传文件只能是 pdf / doc 格式!')
      }
      if (!isLt5M) {
        this.$message.error('上传文件大小不能超过 5MB!')
      }
      // console.log(isJPG && isLt5M)

      return isFile && isLt5M
    }, // 提交表单创建合同
    async confirmAdd() {
      const obj = {
        ...this.rentForm
      }
      obj.startTime = this.rentForm.rentTime[0]
      obj.endTime = this.rentForm.rentTime[1]
      delete obj.rentTime
      this.title === '续租合同' ? obj.type = 1 : obj.type = 0

      const res = await createRentAPI(obj)
      console.log(res)
      this.$message.success(`${this.title}成功`)
      // 更新列表
      this.getList()
      // 关闭弹窗
      this.rentDialogVisible = false
      // 重置表单
      this.$refs.addForm.resetFields()
      this.rentForm.contractUrl = ''
      this.rentForm.contractId = ''
      this.contractList = []
    }, // 监听展开行打开或关闭事件
    async expandHandle(row, rows) {
      // row:当前展开/关闭的这行数据对象
      // rows:所有展开行的数据对象
      // console.log(row, rows)
      // 目标：展开时发请求
      if (rows.includes(row)) {
        const res = await getRentListAPI(row.id)
        // console.log(res)
        // eslint-disable-next-line require-atomic-updates
        row.list = res.data
      }
    }, // 格式化合同状态样式
    formatterStatus(status) {
      // console.log(status)
      const statusObj = {
        0: 'warning',
        1: 'success',
        2: 'info',
        3: 'danger'
      }
      return statusObj[status]
    }, // 退租
    async backRentFn(id) {
      this.$confirm('确认退租吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await outRentAPI(id)
        this.getList()
        this.$message({
          type: 'success',
          message: '退租成功!'
        })
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.department-container {
  padding: 10px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  ;
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}
.create-container{
  margin: 10px 0px;
}
.page-container{
  padding:4px 0px;
  text-align: right;
}
.form-container{
  padding:0px 80px;
}
</style>
